package cn.com.dreamtouch.magicbox_common.helper;

import android.net.wifi.WifiManager;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by MuHan on 17/2/24.
 */

public class UdpHelper implements Runnable {
    public   Boolean IsThreadDisable = false;//指示监听线程是否终止
    private static WifiManager.MulticastLock lock;
    InetAddress mInetAddress;
    private int localPort;
    private DatagramSocket datagramSocket;
    private  volatile List<String>receivedMessageList=new ArrayList<>();
    public UdpHelper(WifiManager manager,int localPort) {
        this.lock= manager.createMulticastLock("UDPwifi");
        this.localPort=localPort;
    }
    public synchronized List<String>getReceivedMessageList()
    {
        List<String> temp=new ArrayList<>();
        temp.addAll(receivedMessageList);//克隆
         receivedMessageList.clear();//已读清除记录
        return temp;
    }
    public void startListen()  {
        // UDP服务器监听的端口
        // 接收的字节大小，客户端发送的数据不能超过这个大小
        byte[] message = new byte[255];
        if(datagramSocket==null)
            return ;
        try {
            // 建立Socket连接
            datagramSocket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(message,
                    message.length);
            try {
                while (!IsThreadDisable) {
                    // 准备接收数据

                        Log.d("UDP ", "准备接受");
                        this.lock.acquire();

                        datagramSocket.receive(datagramPacket);
                        String strMsg = new String(datagramPacket.getData()).trim();
                        receivedMessageList.add(strMsg);
                        Log.d("UDP ", datagramPacket.getAddress()
                                .getHostAddress().toString()
                                + ":" + strMsg+" "+receivedMessageList.size());
                        try {
                            if (this.lock.isHeld())
                                this.lock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//                    try {
//                        Thread.sleep(10000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }

                datagramSocket.disconnect();
                datagramSocket.close();
            } catch (IOException e) {//IOException
                e.printStackTrace();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }
    public  void send(String destinationIp,int port, @NonNull String message) {
        Log.d("UDP Demo", "UDP发送数据:"+message);
        try {
            if(datagramSocket==null) {
                datagramSocket = new DatagramSocket(null);
                datagramSocket.setReuseAddress(true);
                datagramSocket.bind(new InetSocketAddress(localPort));
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress local = null;
        try {
            local = InetAddress.getByName(destinationIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        int msg_length = message.length();
        byte[] messageByte = message.getBytes();
        DatagramPacket p = new DatagramPacket(messageByte, msg_length, local,
                port);
        try {

            datagramSocket.send(p);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        startListen();
    }
}

